package org.testile.placeholderscript;

import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 *
 * @author hvizmar
 */
public class DateTransformer extends AbstractPatternTransformer {
	
	private final DateTimeFormatter defaultFormat = DateTimeFormat.forPattern("yyyy-MM-dd");

	public DateTransformer() {
		super(Pattern.compile("^TODAY([+-]([\\d]+))?(@([GCYyxweEMDd\\-\\\\/: ]*))?$"));
	}

	@Override
	protected String transformMatch(MatchResult match) {
		boolean isInFuture = isInFuture(match.group(1));
		int days = parseDays(match.group(2));
		DateTime date = isInFuture ? getFutureDate(days) : getPastDate(days);
		DateTimeFormatter format = getFormat(match.group(4));
		return date.toString(format);
	}

	private boolean isInFuture(String plusMinus) {
		return plusMinus != null && plusMinus.startsWith("+");
	}

	private DateTime getFutureDate(int daysInFuture) {
		DateTime date = new DateTime();
		return date.plusDays(daysInFuture);
	}

	private DateTime getPastDate(int daysInPast) {
		DateTime date = new DateTime();
		return date.minusDays(daysInPast);
	}

	private int parseDays(String daysInFuture) {
		if(daysInFuture != null) {
			return Integer.parseInt(daysInFuture);
		}
		return 0;
	}

	private DateTimeFormatter getFormat(String pattern){
		return pattern == null ? defaultFormat : DateTimeFormat.forPattern(pattern);
	}
}
